package com.dlyk.manager;

import com.dlyk.mapper.TTranHistoryMapper;
import com.dlyk.mapper.TTranMapper;
import com.dlyk.mapper.TTranRemarkMapper;
import com.dlyk.model.TTran;
import com.dlyk.model.TTranHistory;
import com.dlyk.model.TTranRemark;
import com.dlyk.query.TranHistoryQuery;
import com.dlyk.query.TranRemarkQuery;
import com.dlyk.util.JWTUtils;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @description:
 * @author: ajie
 * @date: 2024/8/18 16:43:06
 * @version: 1.0
 */
@Component
public class TranManager {

    @Resource
    private TTranHistoryMapper tTranHistoryMapper;

    @Resource
    private TTranMapper tTranMapper;

    @Resource
    private TTranRemarkMapper tTranRemarkMapper;

    @Transactional
    public int saveTranHistoryAndUpdateTran(TranHistoryQuery tranHistoryQuery) {

        TTranHistory tTranHistory = new TTranHistory();

        //把前端提交过来的参数数据对象TranHistoryQuery复制到TTranHistory对象中
        //Spring框架有个工具类BeanUtils可以进行对象的复制,复制的条件要求是：两个对象的字段名要相同，字段的类型也相同，这样才可以复制
        BeanUtils.copyProperties(tranHistoryQuery, tTranHistory);

        //解析jwt得到userId
        Integer loginUserId = JWTUtils.parseJWTByUserId(tranHistoryQuery.getToken());

        tTranHistory.setCreateTime(new Date()); //创建时间
        tTranHistory.setCreateBy(loginUserId); //创建人id

        TTran tTran = new TTran();
        tTran.setId(tranHistoryQuery.getTranId());
        tTran.setEditTime(new Date());
        tTran.setEditBy(loginUserId);
        tTran.setStage(tranHistoryQuery.getStage());
        tTran.setExpectedDate(tranHistoryQuery.getExpectedDate());
        tTran.setMoney(tranHistoryQuery.getMoney());
        tTranMapper.updateByPrimaryKeySelective(tTran);

        return tTranHistoryMapper.insertSelective(tTranHistory);
    }
}
